//
//  TF1to16VideoArea.swift
//  TalkfunSDKDemo
//
//  Created by 莫瑞权 on 2022/5/16.
//  Copyright © 2022 Talkfun. All rights reserved.
//

import UIKit

class TF1to16VideoArea: UIView, UICollectionViewDataSource,UICollectionViewDelegate, TF1to16VideoAreaCellDelegate {
    //双击
    func objectDidDragged(_ vc: TF1to16VideoAreaCell) {
        
        if self.delegate != nil && (self.delegate?.responds(to: #selector(TF1to16VideoAreaDelegate.objectDidDragged(_:))))!{
            self.delegate?.objectDidDragged(vc)
           
        }
    }
    
    func dealSingleTap(_ vc: TF1to16VideoAreaCell) {
        if self.delegate != nil && (self.delegate?.responds(to: #selector(TF1to16VideoAreaDelegate.dealSingleTap(_:))))!{
            self.delegate?.dealSingleTap(vc)
           
        }
    }

    @objc public weak var delegate : TF1to16VideoAreaDelegate?
    
    @objc public var collectionView:TFCollectionView?
    //视频view数组
    @objc public let videoSessionsArray = NSMutableArray()
    @objc public var vc:TF1to16VideoAreaCell?
    //全屏
    @objc public var isFull:Bool = false
    //暂无用户连麦
    @objc public let noUserLianmai = UILabel()
    /**获取课程模式 //课程模式 */
    @objc var pageMode:TalkfunPageMode = TalkfunPageModeCourse
    //显示奖杯
    @objc public var showCup:Bool = false

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.clipsToBounds = false
        self.noUserLianmai.text = "暂无用户连麦"
        self.noUserLianmai.font = UIFont.PingFang(size: 16)
        self.noUserLianmai.textColor = UIColor(red: 114/255.0, green: 121/255.0, blue: 132/255.0, alpha: 1)
        self.noUserLianmai.isHidden = true
        self.noUserLianmai.textAlignment = .center
        self.addSubview(self.noUserLianmai)
    }
    func getSpacing()->CGFloat
    {
        // 平均后的间距
        var fSpacing:CGFloat = 5
       
        if (UIDevice.current.userInterfaceIdiom == .phone)
        {
            fSpacing = 4
        }
        
        return fSpacing
    }
    func getItemSize()->CGSize
    {
        var itemSizeWidth:CGFloat = 185
        // 平均后的间距
        let fSpacing:CGFloat = self.getSpacing()
        if (UIDevice.current.userInterfaceIdiom == .phone)
            {
                itemSizeWidth = 107
            }
        let itemSizeHeight:CGFloat = self.frame.size.height-fSpacing-fSpacing
        return CGSize(width: itemSizeWidth, height: itemSizeHeight)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        self.noUserLianmai.frame = CGRect(x: 0, y: (self.frame.size.height-23)/2.0, width: self.frame.size.width, height: 23)

        if (self.collectionView==nil) {
            //平均后的间距
            let fSpacing:CGFloat = self.getSpacing()
            if (self.pageMode == TalkfunPageModeCourse) {
                let layout = UICollectionViewFlowLayout()
                layout.scrollDirection = .horizontal
                
                layout.itemSize = self.getItemSize()
                //垂直方向时
                layout.minimumInteritemSpacing = 0
                //水平方向时，
                layout.minimumLineSpacing = fSpacing
                self.collectionView = TFCollectionView.init(frame: CGRect(x: fSpacing, y: fSpacing, width: self.frame.size.width, height: self.frame.size.height-fSpacing-fSpacing), collectionViewLayout: layout)
               
            } else if (self.pageMode == TalkfunPageModeKeyNote){
                //主讲模式
                let layout = TFVideoFlowLayout()
                layout.pageMode = self.pageMode
                layout.minimumLineSpacing = fSpacing
                self.collectionView = TFCollectionView.init(frame: CGRect(x: fSpacing, y: fSpacing, width: self.frame.size.width, height: self.frame.size.height-fSpacing-fSpacing), collectionViewLayout: layout)
        
            } else if (self.pageMode == TalkfunPageModeGallery) {
                let layout = UICollectionViewFlowLayout()

                layout.minimumLineSpacing = fSpacing
                layout.itemSize = self.getItemSize()
                self.collectionView = TFCollectionView.init(frame: CGRect(x: fSpacing, y: fSpacing, width: self.frame.size.width, height: self.frame.size.height-fSpacing-fSpacing), collectionViewLayout: layout)
            }
          
             self.collectionView!.clipsToBounds = false
            self.collectionView!.dataSource = self
            self.collectionView!.delegate = self
            
            
            //注册Cell，必须要有
            self.collectionView!.register(TF1to16VideoAreaCell.self, forCellWithReuseIdentifier: "TF1to16VideoAreaCell")
            self.addSubview(self.collectionView!)
            self.collectionView!.reloadData()
            self.collectionView!.backgroundColor = UIColor.clear
            
            if #available(iOS 11.0, *) {
                
                self.collectionView!.contentInsetAdjustmentBehavior = .never
                
            }
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return self.videoSessionsArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TF1to16VideoAreaCell", for: indexPath) as! TF1to16VideoAreaCell
        
        cell.showCup = self.showCup
        cell.ViewWidth = cell.frame.size.width
        cell.ViewHight = cell.frame.size.height

        if (indexPath.row < self.videoSessionsArray.count) {
            let  model = self.videoSessionsArray[indexPath.row] as! TalkfunRtcModel
            cell.model =  model
            cell.delegate = self
        }
        
        return cell;
    }
    
    @objc func exist(_ model:TalkfunRtcModel)->Bool

    {
            //是否已经存在
        var Exist:Bool = false
        for i in 0..<self.videoSessionsArray.count {
           let obj = self.videoSessionsArray[i] as! TalkfunRtcModel
        
        if (obj.xid == model.xid) {
            Exist = true

        }
         
         }
         return Exist
    }
    @objc func removeFromVideo(_ dict:TalkfunRtcModel)
    {
        if(self.isFull){
              if (self.vc != nil) {
                  self.dealSingleTap(self.vc!)
              }
          }
        
        let copy = NSMutableArray.init(array: self.videoSessionsArray)
        for i in 0..<copy.count {
            let model = copy[i] as! TalkfunRtcModel
       
            if (model.xid == dict.xid) {
                self.videoSessionsArray.remove(model)
                break;
                
            }
        }
        self.reloadData()
       
    }
    
    func reloadData()
    {
        if self.collectionView != nil {
            self.collectionView?.reloadData()
        }
    }
    // MARK: 直播结束
   @objc func liveStop()
    {
        self.videoSessionsArray.removeAllObjects()
        self.reloadData()
    }
    //关闭所有人的涂鸦
    func allGraffitiCloses()
    {
        for i in 0..<self.videoSessionsArray.count {
           let model = self.videoSessionsArray[i] as! TalkfunRtcModel
      
            model.drawPower = false
           }
        UIView.performWithoutAnimation {
            self.reloadData()
        }
   
    }
    //所有学生下讲台
   @objc func allTheStudentsWalkedOffThePodium()
    {
        let copy = NSMutableArray.init(array: self.videoSessionsArray)
        for i in 0..<copy.count {
            let model = copy[i] as! TalkfunRtcModel
            
            //等于学生
            if (model.role == .roleeUser) {
                self.videoSessionsArray.remove(model)
                
            }
        }
        
        UIView.performWithoutAnimation {
            self.reloadData()
        }
    }
    //删除讲师
    @objc func removeAdminModel(_ model:TalkfunRtcModel)
    {
        if (model != nil) {
         if(self.isFull){
               if (self.vc != nil) {
                   self.dealSingleTap(self.vc!)
                  
               }
           }
           
          
            if (model.role == .roleSpadmin) {
               self.videoSessionsArray.remove(model)
           }
              
           //局部刷新
            self.reloadData()
        
        }
    }
    @objc func updateModel(_ model:TalkfunRtcModel)
    {
        if (model != nil) {
         if(self.isFull){
             if (self.vc != nil) {
                 self.dealSingleTap(self.vc!)
             }
           }
           
            var  Index:Bool = false
           
           //初始化数据
            for i in 0..<self.videoSessionsArray.count {
         
               let obj = self.videoSessionsArray[i] as!TalkfunRtcModel

               if (obj.xid == model.xid) {
                   Index = true
                   obj.score = model.score
                   obj.audio = model.audio
                   obj.drawPower = model.drawPower
                   obj.video = model.video
                   
               }
           }

           if (Index == false) {
               if ( model.role == .roleSpadmin) {
                   self.videoSessionsArray.insert(model, at: 0)
                 
               }else{
                   self.videoSessionsArray.add(model)
               }
              
           }
           //局部刷新
            self.reloadData()
          
        }
       

    }
    @objc func update1to1Model(_ model:TalkfunRtcModel)

    {
        if (model != nil) {
            if(self.isFull){
                if (self.vc != nil) {
                    self.dealSingleTap(self.vc!)
                }
              }
           
           //初始化数据
            for i in 0..<self.videoSessionsArray.count {
         
               let obj = self.videoSessionsArray[i] as!TalkfunRtcModel

                if (obj.xid == model.xid) {
              
                   obj.score = model.score
                   obj.audio = model.audio
                   obj.drawPower = model.drawPower
                   obj.video = model.video
                   
               }
           }

         
           //局部刷新
            self.reloadData()
        }
    }
    
}
@objc public protocol TF1to16VideoAreaDelegate : NSObjectProtocol {
    //双击了
    func objectDidDragged(_ vc : TF1to16VideoAreaCell)
    //单击
    func dealSingleTap(_ vc : TF1to16VideoAreaCell)
}


class TFVideoFlowLayout: UICollectionViewFlowLayout {

    //记录布局滚动范围
    @objc var contentSizeHeight:CGFloat = 0
    /** 所有的布局属性 */
    @objc var attrsArray = NSMutableArray()

    /**获取课程模式 //课程模式; //视频模式 */
    @objc var pageMode:TalkfunPageMode = TalkfunPageModeCourse
  
    
    override func prepare(){
        super.prepare()
        //主讲模式
        if (self.pageMode == TalkfunPageModeKeyNote)
        {
            
        
            var cellWidth:CGFloat = 185
            // 平均后的间距
            
            if (UIDevice.current.userInterfaceIdiom == .phone)
            {
                cellWidth = 107
            }
            let cellHeight:CGFloat = self.collectionView!.frame.size.height
            
            
            let count1:NSInteger = self.collectionView!.numberOfItems(inSection: 0)
            
            let count:CGFloat = CGFloat(count1)
 
        
            let Allwidth:CGFloat = CGFloat(count*(cellWidth+5))
            self.attrsArray.removeAllObjects()
    
            for i in 0..<count1 {
       
                // 创建UICollectionViewLayoutAttributes
               
                let indexPath = NSIndexPath.init(item: i, section: 0)
                
                
                
                let attrs = UICollectionViewLayoutAttributes.init(forCellWith: indexPath as IndexPath)
                
                let collectionViewWidth = self.collectionView!.frame.size.width
                // 设置布局属性
                var x:CGFloat = (collectionViewWidth-cellWidth*count-(count-1)*5)/2
                if (x>0) {
                    x = (collectionViewWidth-cellWidth*count-(count-1)*5)/2
                } else {
                    x = 0
                }
                if (count == 1) {
                    
                    
                    let xx:CGFloat = (collectionViewWidth - cellWidth*(CGFloat(i)+1)-CGFloat(i)*5) / 2.0
                    attrs.frame = CGRect(x: xx, y: 0, width: cellWidth, height: cellHeight)
                    
                }
                else if (count == 2) {

                    if (i==0) {
                        attrs.frame = CGRect(x: x, y: 0, width: cellWidth, height: cellHeight)
                        
                    } else if (i==1) {
                        attrs.frame = CGRect(x: x+cellWidth+5, y: 0, width: cellWidth, height: cellHeight)
                       
                    }
               
                } else if (count == 3) {
                    if (i==0) {
                        attrs.frame = CGRect(x: x, y: 0, width: cellWidth, height: cellHeight)
                    } else if (i==1) {
                        attrs.frame = CGRect(x: x+cellWidth+5, y: 0, width: cellWidth, height: cellHeight)
                    } else if (i==2) {
                        attrs.frame = CGRect(x: x+cellWidth*2+5*2, y: 0, width: cellWidth, height: cellHeight)
                        
                       
                    }
                } else if (count == 4) {
                    if (i==0) {
                        attrs.frame = CGRect(x: x, y: 0, width: cellWidth, height: cellHeight)
                    } else if (i==1) {
                        attrs.frame = CGRect(x: x+cellWidth+5, y: 0, width: cellWidth, height: cellHeight)
                        
                    
                    } else if (i==2) {
                        
                       
                        attrs.frame =  CGRect(x: x+cellWidth*2+5*2, y: 0, width: cellWidth, height: cellHeight)
                    } else if (i==3) {
                        
                        
                        attrs.frame = CGRect(x: x+cellWidth*3+5*3, y: 0, width: cellWidth, height: cellHeight)
                    }
                } else if (count == 5) {
                    if (i==0) {
                        attrs.frame = CGRect(x: x, y: 0, width: cellWidth, height: cellHeight)
                    } else if (i==1) {
                        
                        
                        
                        attrs.frame = CGRect(x: x+cellWidth+5, y: 0, width: cellWidth, height: cellHeight)
                    } else if (i==2) {
                       
                        attrs.frame =  CGRect(x: x+cellWidth*2+5*2, y: 0, width: cellWidth, height: cellHeight)
                    } else if (i==3) {
                       
                        attrs.frame =  CGRect(x: x+cellWidth*3+5*3, y: 0, width: cellWidth, height: cellHeight)
                    } else if (i==4) {
                       
                        attrs.frame =  CGRect(x: x+cellWidth*4+5*4, y: 0, width: cellWidth, height: cellHeight)
                    }
                } else {
                    if (Allwidth < collectionViewWidth) {
                        
                        attrs.frame = CGRect(x:(collectionViewWidth-Allwidth)/2.0+(cellWidth+5)*CGFloat(i), y: 0, width: cellWidth, height: cellHeight)
                    } else {
                        
                        attrs.frame = CGRect(x:(cellWidth+5)*CGFloat(i), y: 0, width: cellWidth, height: cellHeight)
                    }
                   
                }
       
//                NSLog("frame====>%@", NSCoder.string(for: attrs.frame))
                self.attrsArray.add(attrs)
                
            }
            if (self.attrsArray.count > 0){
                let lastAttrs = self.attrsArray.lastObject as! UICollectionViewLayoutAttributes
                            self.contentSizeHeight = lastAttrs.frame.maxY;
            }

        }
    }
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        return (self.attrsArray as! [UICollectionViewLayoutAttributes]);
    }
    //此方法会计算并返回每个item的位置和大小，换句话说就是collectionView里面的布局是怎样布局的就根这个方法的返回值有关

    override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
        return true
    }

}
